import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import {
  Card,
  Row,
  Col,
  Select,
  Radio,
  Button,
} from 'antd';
import { Form } from '@ant-design/compatible';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { DownloadOutlined } from '@ant-design/icons';

import PageHeader from '@/components/PageHeader';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;

const sizeInfos = [
  {
    name: '大尺寸',
    width: 1000,
    height: 1000,
  },
  {
    name: '中等尺寸',
    width: 500,
    height: 500,
  },
  {
    name: '小尺寸',
    width: 300,
    height: 300,
  },
];

interface TableProps extends FormComponentProps {
  dispatch: Dispatch;
  location: { query: any };
  codeUrl: string;
  logisInfo: any;
  INITINFO: any;
}

interface TableState {
  size: number;
}

@connect(({
  tookManagementQrCode: { logisInfo, codeUrl },
  common: { INITINFO },
}: any) => ({
  logisInfo,
  codeUrl,
  INITINFO,
}))

class TookManagementElem extends React.Component<TableProps, TableState> {
  state = {
    size: 0,
  }

  componentDidMount() {
    this.fetchLogisList();
  }

  /**
   * 获取物流中心列表
   */
  fetchLogisList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchLogisList',
    });
  }

  /**
   * 选择物流中心
   */
  changeLogis = (logisId: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tookManagementQrCode/fetch',
      payload: { id: logisId },
    });
  }

  /**
   * 改变二维码下载尺寸
   */
  changeType = (e: any) => {
    this.setState({ size: e.target.value });
  }

  /**
   * 下载二维码
   */
  handleDownLoad = () => {
    const { size } = this.state;
    const { logisInfo, codeUrl } = this.props;

    const { width, height } = sizeInfos[size];
    const imageInfo = {
      width,
      height,
      type: 1,
      logisId: logisInfo.id,
    };

    window.location.href = `${codeUrl}?${qs.stringify(imageInfo)}`;
  }

  render() {
    const { size } = this.state;

    const {
      form: { getFieldDecorator },
      logisInfo,
      codeUrl,
      INITINFO: { logisList },
    } = this.props;

    const { width, height } = sizeInfos[size];
    const imageInfo = {
      width,
      height,
      type: 0,
      logisId: logisInfo.id,
    };
    const qrCodeUrl = logisInfo.sendByStoreStatus
      ? `${codeUrl}?${qs.stringify(imageInfo)}`
      : '';

    let tipsText = '请选择物流中心';
    if (logisInfo.sendByStoreStatus !== undefined) {
      tipsText = logisInfo.sendByStoreStatus
        ? `${logisInfo.name}门店寄件二维码`
        : '该物流中心未开启门店寄件服务，无法生成门店寄件二维码';
    }

    return (
      <>
        <PageHeader />
        <Card bordered={false} className="searchForm">
          <Form hideRequiredMark={false} className="tableListForm">
            <Row gutter={12}>
              <Col md={8} sm={24}>
                <Form.Item label="物流中心" style={{ flexWrap: 'inherit' }}>
                  {getFieldDecorator('logisId')(
                    <Select
                      showSearch
                      placeholder="请选择"
                      onChange={this.changeLogis}
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {logisList.map((item: any) => (
                        <Option value={item.id} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>
        <Card bordered={false} title="生成门店寄件二维码">
          <Row gutter={12}>
            <Col span={24}>
              {!!logisInfo.sendByStoreStatus && (
                <div
                  style={{
                    width: '240px',
                    height: '240px',
                    border: '1px solid #eee',
                  }}
                >
                  <img src={qrCodeUrl} alt="二维码" style={{ width: '100%', height: '100%' }} />
                </div>
              )}
              <div className="marginT20">{tipsText}</div>
            </Col>
          </Row>
          <Row gutter={12} className="marginT20">
            <Col span={24}>
              <Radio.Group onChange={this.changeType} value={size}>
                {sizeInfos.map((item: any, index: number) => (
                  <Radio value={index} key={item.name}>
                    {item.name}({item.width}*{item.height})
                  </Radio>
                ))}
              </Radio.Group>
            </Col>
          </Row>
          <Row gutter={12} className="marginT20">
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              size="large"
              disabled={!logisInfo.sendByStoreStatus}
              onClick={this.handleDownLoad}
            >
              下载二维码
            </Button>
          </Row>
        </Card>
      </>
    );
  }
}

export default Form.create<TableProps>()(TookManagementElem);
